/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.console.config;

import java.io.OutputStream;
import java.io.PrintStream;

public class OIConsole extends PrintStream {
    //private static OIPrintStream out;
    //private static OIPrintStream err;
    private static OIConsole real;

    /***
     * Intercept System.out.println()
     */
    public static void load() {
        real = new OIConsole(System.out);
        System.setOut(new OIConsole(System.out));
        System.setErr(new OIConsole(System.err));
    }

    public OIConsole(OutputStream out) {
        super(out);
    }

    public static void console(String x) {
        real.println(x);
    }

    public static void console(String x, int indent) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < indent; i++) {
            stringBuilder.append(" ");
        }
        stringBuilder.append(x);
        console(stringBuilder.toString());
    }

    @SuppressWarnings("unused")
    public static void println2console(String x) {
        console("");
        console(x);
        console(LineReaderConfig.prompt);
    }

    @Override
    public void print(int i) {
    }

    @Override
    public void print(boolean b) {
    }

    @Override
    public void print(char c) {
    }

    @Override
    public void print(long l) {
    }

    @Override
    public void print(float f) {
    }

    @Override
    public void print(double d) {
    }

    @Override
    public void print(char[] s) {
    }

    @Override
    public void print(Object obj) {
    }

    @Override
    public PrintStream append(CharSequence csq, int start, int end) {
        return this;
    }

    @Override
    public void write(int b) {
    }

    /***
     * Intercept non-{@link #console(String)} print
     */
    @Override
    public void write(byte[] buf, int off, int len) {
        if (this != real) return;
        super.write(buf, off, len);
    }
}
